package com.face.service;

import com.face.common.Page;
import com.face.dao.AccountDao;
import com.face.dao.RoleDao;
import com.face.dao.UserDao;
import com.face.entity.Remark;
import com.face.entity.Role;
import com.face.entity.User;
import com.face.entity.Visit;
import com.face.exception.*;
import com.face.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by czh on 17-7-2.
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RemarkService remarkService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private VisitService visitService;

    @Transactional(rollbackFor = Exception.class)
    public int saveUser(User user, Remark remark) {

        String userId = userDao.saveUser(user);

        Visit visit = new Visit();
        visit.setUserId(userId);
        visit.setShopId(user.getShopId());
        visit.setUsername(user.getUsername());
        visit.setLoginTime(new Timestamp(System.currentTimeMillis()));
        shopService.saveVisit(visit);

        remark.setUserId(userId);
        int id = remarkService.saveRemark(remark);
        if (id < 0) {
            throw new DatabaseException("remark", "save", "remark");
        }

        return id;
    }

    public Integer updateUser(User user) {
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        return userDao.updateUser(user);
    }

    public UserWrapper getUserById(String userId) {
        if (userId == null) {
            throw new ArgumentException("参数不对");
        }
        User user = userDao.getUserById(userId);
        if (user == null) {
            throw new ServiceException("查不到 用戶");
        }
        UserWrapper wrapper = new UserWrapper();
        wrapper.setId(user.getId());
        wrapper.setType(user.getType());
        wrapper.setGroup(user.getGroup());
        wrapper.setAge(user.getAge());
        wrapper.setCreateTime(user.getCreateTime());
        wrapper.setCreator(user.getCreator());
        wrapper.setGender(user.getGender());
        wrapper.setImgPath(user.getImgPath());
        wrapper.setIsDelete(user.getIsDelete());
        wrapper.setJob(user.getJob());
        wrapper.setShopId(user.getShopId());
        wrapper.setUpdateTime(user.getUpdateTime());
        wrapper.setUserId(user.getUserId());
        wrapper.setUsername(user.getUsername());
        wrapper.setMobilephone(user.getMobilephone());
        return wrapper;
    }

    public Page<User> listAll(String shopId, Integer page, Integer limit, String start, String end, String sort,
                              String order, String username, String type, String creator) {
        String orderClause = new String("");
        if (sort == null || sort.isEmpty()) {
            orderClause += "updateTime";
        }
        if (order == null || order.isEmpty()) {
            orderClause += " ";
            orderClause += "desc";
        }

        if (start == null || start.isEmpty() || end == null || end.isEmpty()) {
            return userDao.listAll(shopId, page, limit, orderClause, username, type, creator);
        }
        return userDao.list(shopId, page, limit, start, end, orderClause, username, type, creator);
    }

    public Integer count(String shopId, String start, String end) {
        return userDao.count(shopId, start, end);
    }

    public Integer count(String shopId) {
        return userDao.count(shopId);
    }

    public UserWrapper findByUserId(String userId) {
        return userDao.findByUserId(userId);
    }

    public Map<String, Object> findDetailByUserId(String openid, String userId) {
        UserWrapper userWrapper = determineAuthority(openid, userId);
        userWrapper.setOpenId(null);
        userWrapper.setShopId(null);
        userWrapper.setCreator(null);
        userWrapper.setIsDelete(null);
        userWrapper.setRemarkList(remarkService.getRemarksByUserId(userId, 3));
        Map<String, Object> model = new HashMap<>();
        model.put("customer", userWrapper);
        return model;
    }

    public Page<User> findUserListByOpenid(String openid, Integer page, Integer limit) {

        Role role = roleDao.findByOpenid(openid);
        if ("超级管理员".equals(role.getName())) {
            return userDao.findUserForManager(role.getShopId(), page, limit, "updateTime");
        }

        String username = accountDao.findUsernameByOpenid(openid);
        return userDao.findUserByCreator(username, page, limit, "updateTime");
    }

    public UserWrapper determineAuthority(String openid, String userId) {

        UserWrapper user = userDao.findByUserId(userId);
        if (user == null || StringUtils.isEmpty(user.getUserId())) {
            throw new ServiceException("顾客不存在");
        }
        if (openid.equals(user.getOpenId())) {
            return user;
        }
        Role role = roleDao.findByOpenid(openid);
        if (!"超级管理员".equals(role.getName())) {
            throw new InsufficientPrivilegesException("权限不足");
        }
        return user;

    }

    public Map<String, Object> findByUserIdOnWechat(String openid, String userId) {

        determineAuthority(openid, userId);

        return visitService.findForWechatToRemark(userId);
    }

    public Map<String, List<User>> group(String shopId, Integer type) {
        List<User> list = userDao.findAll(shopId);
        if (type == 0) {
            return list.stream().collect(Collectors.groupingBy(User::getType));
        } else if(type == 1){
            return list.stream().collect(Collectors.groupingBy(User::getCreator));
        }
        return null;
    }
}
